package com.breaktian.assemble.socket.udt;

import java.io.IOException;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import udt.UDTClient;
import udt.UDTReceiver;


/**
 * @author breaktian
 * udt协议
 * udt客户端
 * */
public class UdtSocket {
	
	
	private UDTClient udtClient;

	/**
	 * 端口是系统随机分配
	 * */
	public UdtSocket(){
		try {
			UDTReceiver.dropRate = 0;
			udtClient = new UDTClient(InetAddress.getLocalHost());
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}
	
	public UdtSocket(int port){
		try {
			udtClient = new UDTClient(InetAddress.getLocalHost(), port);
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}
	
	public UdtSocket connect(String remoteIp, int remotePort){
		if(udtClient==null) throw new IllegalStateException("udtclient为null");
		try {
			udtClient.connect(remoteIp, remotePort);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return this;
	}
	
	
	
	/**
	 * 发送字符串
	 * */
	public void send(String s){
		if(s==null||s.length()<1) throw new IllegalStateException("发送的数据为空");
		byte[] sendData = s.getBytes();
		try {
			udtClient.sendBlocking(sendData);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 发送字符数组
	 * */
	public void send(byte[] data){
		if(data==null||data.length<1) throw new IllegalStateException("发送的数据为空");
		try {
			udtClient.sendBlocking(data);
			udtClient.shutdown();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 关闭客户端socket
	 * */
	public void close(){
		try {
			udtClient.shutdown();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
}
